package com.fishingwithme.android.ui.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.fishingwithme.android.data.model.CircleDetail
import com.fishingwithme.android.data.model.SpotInCircleDto
import com.fishingwithme.android.data.repository.FishingRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

data class CircleDetailUiState(
    val isLoading: Boolean = true,
    val detail: CircleDetail? = null,
    val error: String? = null
)

@HiltViewModel
class CircleDetailModel @Inject constructor(
    private val repository: FishingRepository
) : ViewModel() {
    private val _uiState = MutableStateFlow(CircleDetailUiState())
    val uiState: StateFlow<CircleDetailUiState> = _uiState.asStateFlow()
    
    private var currentCircleId: String = ""

    fun getCircleDetail(id: String) {
        currentCircleId = id
        
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, error = null) }

            try {
                val spotFlow =
                    repository.loadCircleDetail(id)

                spotFlow.collect { result ->
                    result.fold(
                        onSuccess = { detail ->
                            _uiState.update {
                                it.copy(
                                    isLoading = false,
                                    detail = detail,
                                    error = null
                                )
                            }
                        },
                        onFailure = { throwable ->
                            _uiState.update {
                                it.copy(
                                    isLoading = false,
                                    error = throwable.message ?: "加载详情失败"
                                )
                            }
                        }
                    )
                }
            } catch (e: Exception) {
                _uiState.update {
                    it.copy(
                        isLoading = false,
                        error = e.message ?: "未知错误"
                    )
                }
            }
        }
    }
    
    fun getCircleSpots(): Flow<PagingData<SpotInCircleDto>> {
        return Pager(
            config = PagingConfig(
                pageSize = 20,
                enablePlaceholders = false
            ),
            pagingSourceFactory = { CircleSpotsPagingSource(repository, currentCircleId) }
        ).flow
    }
}